# -*- coding: UTF-8 -*-
import datetime
from itertools import groupby
import os
import time
from lj_action import action_data, action_ai, action_event, action_fm
from lj_tool import lj_bean_conn, tool_arr, tool_json, tool_log, tool_minio, tool_run, tool_ssh, tool_str, tool_try
from lj_tool.tool_opt import v
from lj_orm import tool_ai
import json

ai_record_action = action_data.init_action_data(
    "ai_record", "272ab1b9c5cc4ea2b76302238247284c")


ai_result = action_data.init_action_data(
    "airesult", "272ab1b9c5cc4ea2b76302238247284c")

ai_record_entity = ai_record_action.entity
ai_result_entity = ai_result.entity

event_code_bind_ai_mode = {
    "Person": "machine-vision-personnel-intrusion",
    "WaterGarbage": "machine-vision-water-garbage-intrusion",
    "Water": "machine-vision-water-intrusion",
    "VehicleType": "machine-vision-vehicle-intrusion",
    "Algae": "machine-vision-algae-intrusion",
    "All": "machine-vision-all-intrusion",
}


def group_key(file):
    print(file.get("filename"))
    splits = file.get("filename").split("-")
    if len(splits) < 4:
        return
    return splits[0] + splits[1] + splits[2] + splits[3]


@tool_try.lj_no_except
def job():
    """机器视觉结果处理任务
    """
    print("LJ - 开始运行AI视频分析任务...")
    # AI服务器列表
    ai_analysis_servers = action_ai.list_ai_server()
    if len(ai_analysis_servers) < 1:
        tool_log.error("LJ - 无可用AI服务器...")
        return

    for server in ai_analysis_servers:
        remote_file_list = tool_ssh.list_file_and_children(lj_bean_conn.init_ai_server(server), "D:/AI_result")

        # 文件分组,先排序后分组
        group_file = tool_arr.group_by(remote_file_list, group_key)

        for group in group_file.values():
            __handle(server, list(group))


def __handle(server, files):
    group_file = {os.path.splitext(file.get("filename"))[
        1][1:]: file for file in files}
    if group_file.get("json") and group_file.get("jpg"):

        json = group_file.get("json")
        file = group_file.get("jpg")

        # 判断如果是在线文件直接返回，不进行处理
        if "ai-online-analysis" in json.get("filename"):
            return

        # 读取json文件,并对数据进行中文编码
        bcontent = tool_ssh.read_file(lj_bean_conn.init_ai_server(
            server), json.get("path"))
        if not bcontent:
            return

        content = bcontent.decode()

        mode_type_tag = is_have_alert_things(content)

        # 从数据库查询待获取结果数据
        ai_records = ai_record_entity.select().where(
            ai_record_entity.file_name == file.get('filename'))

        for ai_record in ai_records:
            # 为此记录赋值
            ai_record.text_json = content
            dict_row = {"id": ai_record.id}

            if not mode_type_tag or "无" == mode_type_tag:
                dict_row["is_exception"] = 'false'
            else:
                dict_row["is_exception"] = 'true'
                dict_row["text_json"] = content
                # 保存文件
                link_url = save_to_minio(server, file)
                dict_row["link_url"] = link_url
                # 记录赋值
                ai_record.link_url = link_url
                # 兼容旧逻辑
                handle_old(mode_type_tag, ai_record)
                # 获取对应模型
                model = action_ai.get_model_by_code(ai_record.ai_mode_type)

                # 获取对应运维人员
                om_user = action_fm.get_om_user_by_mn(ai_record.point_code)
                om_dict = {}
                if om_user:
                    om_dict["handler"] = om_user.id
                    om_dict["handler_name"] = om_user
                val = tool_ai.get_val_by_code(tool_ai.ConfigCode.MSG_PUSH)
                json_obj = json.loads(val)
                is_open = bool(json_obj['open'])
                if is_open:
                    # 生成告警事件
                    action_event.alarm_event(
                        alarm_event_code=event_code_bind_ai_mode.get(
                            ai_record.ai_mode_type),
                        alarm_title=f"机器视觉 - [{mode_type_tag}]预警",
                        alarm_desc=f"您的基站[{ai_record.point_code}]与[{ai_record.analytics_time}]由AI智能视觉分析察觉异常[{model.name}]，特进行预警处理，请尽快核实处理。",
                        handler_type="2",
                        source_code="富铭科技-机器视觉",
                        point_code=ai_record.point_code,
                        alarm_file=ai_record.link_url,
                        point_name=v(action_fm.get_site_by_mn(
                            ai_record.point_code), "site_name"),
                        **om_dict
                    )

            # 更新数据
            ai_record_action.sync(dict_row)

    for item in files:
        # 删除执行过的文件
        tool_ssh.remove_file(
            lj_bean_conn.init_ai_server(server), item.get("path"))
        time.sleep(0.5)


def handle_old(mode_type_tag, ai_record):
    # 验证十分钟内是否有告警
    ten_minutes_ago = datetime.datetime.now() - datetime.timedelta(minutes=10)

    list = ai_result_entity.select().where((ai_result_entity.create_time > ten_minutes_ago) & (ai_result_entity.site_mn ==
                                           ai_record.point_code) & (ai_result_entity.ai_mode_type == ai_record.ai_mode_type))

    if len(list) < 1:
        ai_result.sync({
            "image_name": ai_record.file_name,
            "site_mn": ai_record.point_code,
            "camera_index_code": ai_record.camera_index_code,
            "image_url": ai_record.link_url,
            "is_alert": "1",
            "alert_type": mode_type_tag,
            "ai_mode_type": ai_record.ai_mode_type,
            "text_json": ai_record.text_json,
            "analytics_time": ai_record.file_name.split("-")[2],
            "create_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        })


def save_to_minio(server, file):

    filename = file.get("filename")
    path = tool_ssh.get_file(lj_bean_conn.init_ai_server(
        server), file.get("path"), filename)

    # 创建远程文件
    today = datetime.datetime.now().strftime("%Y%m%d")

    tool_ssh.send_file(lj_bean_conn.BeanConn("61.52.247.249", "file_server", "-x}{d#-l=tMR", 12000),
                       path,
                       f"/com/nginx/www/file/{today}/{filename}")

    return f"http://http.zzfmhb.com:12080/file/{today}/{filename}"
    # return tool_minio.init_default().put_object("ai-vision", file.get("filename"), path)


# @tool_try.lj_no_except
def is_have_alert_things(json_str):
    if isinstance(json_str, str):
        json_data = tool_json.lj_json_loads(json_str)
        if isinstance(json_data, list) and len(json_data) > 0:
            things = []
            for item in json_data:
                if isinstance(item, dict) and "物体" in item:
                    things.append(item["物体"])
            return ",".join(things)

# job()
# 定时任务
val = tool_ai.get_val_by_code(tool_ai.ConfigCode.FREQUENCY)
tool_run.do(job, int(val))
tool_run.start()
